<?php

namespace app\admin\command;

use addons\thirdwork\library\Application;
use app\admin\model\Payslip;
use app\admin\model\PayslipLogs;
use app\admin\model\PayslipSend;
use app\admin\model\User;
use app\admin\model\UserDepartment;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;

class Cronjob extends Command
{
	protected $model = NULL;

	protected function configure()
	{
		$this->setName('cronjob')
		     ->addOption('name', 'j', Option::VALUE_REQUIRED, '任务名称', NULL)
		     ->setDescription('计划任务');
	}

	protected function execute(Input $input, Output $output)
	{
		$jobname = $input->getOption('name') ?: '';
		if (method_exists($this, $jobname)) {
			$output->highlight('[' . date('Y-m-d H:i:s') . '] 检查任务锁');
			$fileTmpDir = RUNTIME_PATH . 'lock' . DS;
			if (!is_dir($fileTmpDir)) {
				@mkdir($fileTmpDir, 0755, TRUE);
			}
			$filelock = fopen($fileTmpDir . $jobname . '.lock', 'w+'); //加锁
			if (flock($filelock, LOCK_EX | LOCK_NB)) { //TODO 执行业务代码
				$output->highlight('[' . date('Y-m-d H:i:s') . '] 开始任务');
				/**************************************/
				$this->$jobname($input, $output);
				/**************************************/
				flock($filelock, LOCK_UN);//解锁
				$output->highlight('[' . date('Y-m-d H:i:s') . '] 任务完成');
			} else { //TODO 执行业务代码 返回系统繁忙等错误提示
				$output->highlight('[' . date('Y-m-d H:i:s') . '] 有相同的任务正在运行');
			}
			fclose($filelock); //关闭文件
		}
	}

	/**
	 * 处理同步部门(每5分钟执行)
	 * cd /www/wwwroot/gongzi.shjrv.cn/ && php think cronjob --name=handleSyncDepartment
	 * cd /Users/William/MyCode/MyPHPCode/gongzi.jrvtest.com/ && php think cronjob --name=handleSyncDepartment
	 * d:/BtSoft/php/72/php.exe d:/wwwroot/gongzi.jrvtest.com/think cronjob --name=handleSyncDepartment
	 */
	protected function handleSyncDepartment(Input $input, Output $output)
	{
		UserDepartment::syncData($output);
		$output->info('[' . date('Y-m-d H:i:s') . '] 处理同步部门完成');
	}

	/**
	 * 处理同步员工(每5分钟执行)
	 * cd /www/wwwroot/gongzi.shjrv.cn/ && php think cronjob --name=handleSyncUser
	 * cd /Users/William/MyCode/MyPHPCode/gongzi.jrvtest.com/ && php think cronjob --name=handleSyncUser
	 * d:/BtSoft/php/72/php.exe d:/wwwroot/gongzi.jrvtest.com/think cronjob --name=handleSyncUser
	 */
	protected function handleSyncUser(Input $input, Output $output)
	{
		User::syncData($output);
		$output->info('[' . date('Y-m-d H:i:s') . '] 处理同步员工完成');
	}

	/**
	 * 处理工资通知(每1分钟执行)
	 * cd /www/wwwroot/gongzi.shjrv.cn/ && php think cronjob --name=handleSendNotice
	 * cd /Users/William/MyCode/MyPHPCode/gongzi.jrvtest.com/ && php think cronjob --name=handleSendNotice
	 * d:/BtSoft/php/72/php.exe d:/wwwroot/gongzi.jrvtest.com/think cronjob --name=handleSendNotice
	 */
	protected function handleSendNotice(Input $input, Output $output)
	{
		$time = time();
		$list = (new Payslip)->where(['status' => ['in', '1, 2'], 'estimatetime' => ['<', $time]])->column('id, title');
		if ($list) {
			$config = config('site.payslip_config');
			$app    = new Application(get_addon_config('thirdwork'));
			$max    = 100;
			foreach ($list as $id => $title) {
				$logs = (new PayslipLogs)->alias('p')
				                         ->join('user u', 'u.id = p.user_id', 'LEFT')
				                         ->where(['payslip_id' => $id, 'user_id' => ['>', 0]])
				                         ->column('p.id, u.username');
				if ($logs) {
					$groups = array_chunk($logs, $max, TRUE);
					foreach ($groups as $group) {
						$logs_ids = array_keys($group);
						$user_ids = implode('|', $group);
						$data     = [
							[
								'title'       => $title,
								'description' => $config['zhaiyao'],
								'url'         => url('/index/index/index', ['first' => 'yes'], TRUE, config('site.domain')),
								'picurl'      => cdnurl($config['image'], config('site.domain'))
							]
						];
						$output->info('[' . date('Y-m-d H:i:s') . '] ' . $title . '：发送完成');
						$res = $app->wechatwork->sendNewsMessage($data, $user_ids);
						//记录发送日志
						$logs = [
							'user_ids'  => $user_ids,
							'request'   => $res['request'],
							'response'  => $res['response'],
							'status'    => $res['code'] ? 1 : 2,
							'manage_id' => 0
						];
						PayslipSend::create($logs);
						PayslipLogs::update(['status' => ($res['code'] ? 2 : 3), 'sendtime' => time()], ['id' => ['in', $logs_ids]]);
					}
					Payslip::update(['status' => 3, 'sendtime' => time()], ['id' => $id]);
				}
			}
		}
		$output->info('[' . date('Y-m-d H:i:s') . '] 处理工资通知完成');
	}

	/**
	 * 处理工资自动确认
	 * cd /www/wwwroot/gongzi.shjrv.cn/ && php think cronjob --name=handleAutoView
	 * cd /Users/William/MyCode/MyPHPCode/gongzi.jrvtest.com/ && php think cronjob --name=handleAutoView
	 * d:/BtSoft/php/72/php.exe d:/wwwroot/gongzi.jrvtest.com/think cronjob --name=handleAutoView
	 */
	protected function handleAutoView(Input $input, Output $output)
	{
		$config = config('site.payslip_config');
		if ($config['open_auto_confirm'] && $config['auto_confirm_hours'] >= 1) {
			$time = time() - $config['auto_confirm_hours'] * 3600;
			PayslipLogs::update(['is_view' => 1], ['sendtime' => ['<', $time]]);
		}
		$output->info('[' . date('Y-m-d H:i:s') . '] 处理自动确认完成');
	}

	/**
	 * 处理工资确认提醒
	 * cd /www/wwwroot/gongzi.shjrv.cn/ && php think cronjob --name=handleViewNotice
	 * cd /Users/William/MyCode/MyPHPCode/gongzi.jrvtest.com/ && php think cronjob --name=handleViewNotice
	 * d:/BtSoft/php/72/php.exe d:/wwwroot/gongzi.jrvtest.com/think cronjob --name=handleViewNotice
	 */
	protected function handleViewNotice(Input $input, Output $output)
	{
		$config = config('site.payslip_config');
		if ($config['auto_notice_hours'] && $config['auto_notice_hours'] >= 1) {
			$time = time() - $config['auto_notice_hours'] * 3600;
			$list = (new PayslipLogs)->alias('p')
			                         ->join('user u', 'u.id = p.user_id', 'LEFT')
			                         ->where(['p.is_view' => 0, 'p.is_notice' => 0, 'p.status' => 2, 'p.user_id' => ['>', 0], 'p.sendtime' => ['<', $time]])
			                         ->column('p.id, u.username');
			if ($list) {
				$app    = new Application(get_addon_config('thirdwork'));
				$max    = 100;
				$groups = array_chunk($list, $max, TRUE);
				foreach ($groups as $group) {
					$logs_ids = array_keys($group);
					$user_ids = implode('|', $group);
					$content  = '您有一条<a href="' . url('/index/index/index', ['first' => 'yes'], TRUE, config('site.domain')) . '">工资发放记录</a>还未查看。';
					$app->wechatwork->sendTextMessage($content, $user_ids);
					PayslipLogs::update(['is_notice' => 1], ['id' => ['in', $logs_ids]]);
				}
			}
		}
		$output->info('[' . date('Y-m-d H:i:s') . '] 处理工资提醒完成');
	}
}
